//
//  UIView+Mask.m
//  Whatnet_iOS
//
//  Created by 北辰 on 2019/4/24.
//  Copyright © 2019 什么网络. All rights reserved.
//

#import "UIView+Mask.h"
#import <objc/runtime.h>

@implementation UIView (Mask)
/**
 设置左上角和右上角的圆角

 @param cornerR 圆角半径
 */
- (void)cornerTopLeftAndTopRight:(CGFloat)cornerR byRoundingCorners:(UIRectCorner)corners
{
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(cornerR, cornerR)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

//添加背景渐变  horizontal:水平渐变 还是垂直渐变
- (void)addGradientLayerStartColor:(NSInteger)startColor endColor:(NSInteger)endColor horizontal:(BOOL)horizontal{
    [self addGradientLayerStartColor:startColor endColor:endColor horizontal:YES alpha:1];
}

- (void)addGradientLayerStartColor:(NSInteger)startColor endColor:(NSInteger)endColor horizontal:(BOOL)horizontal alpha:(CGFloat)alpha{
    CAGradientLayer *gl = objc_getAssociatedObject(self, @selector(addGradientLayerStartColor:endColor:horizontal:));
    if (!gl) {
        gl = [CAGradientLayer layer];
        objc_setAssociatedObject(self, @selector(addGradientLayerStartColor:endColor:horizontal:), gl, OBJC_ASSOCIATION_ASSIGN);
    }
    [gl removeFromSuperlayer];
    gl.frame = self.bounds;
    if (horizontal) {
        gl.startPoint = CGPointMake(1, 0);
    }else{
        gl.startPoint = CGPointMake(0, 1);
    }
    UIColor *startCo = [WNHexColor(startColor) colorWithAlphaComponent:alpha];
    UIColor *endCo = [WNHexColor(endColor ) colorWithAlphaComponent:alpha];
    gl.locations = @[@(0.0),@(1.0f)];
    gl.endPoint = CGPointMake(0, 0);
    gl.colors = @[(__bridge id)startCo.CGColor,(__bridge id)endCo.CGColor];
    gl.locations = @[@(0.0),@(1.0f)];
    [self.layer insertSublayer:gl atIndex:(unsigned)(self.layer.sublayers.count - 1)];
}

-(void)removeAllSubViews{
    
    for (UIView *subview in self.subviews){
        [subview removeFromSuperview];
    }
    
}
@end
